package com.holly.common_view.view;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;

/**
 * 广告轮播
 *
 * @author Joey Huang（QQ:273179370）
 * @created 2016/7/26
 */
public class AutoPlayViewPager extends ViewPager {
    public AutoPlayViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoPlayViewPager(Context context) {
        this(context, null);
    }

    /**
     * 开始轮播
     */
    public void start() {
        stop();
        postDelayed(play, timeMillis);
    }

    /**
     * 停止轮播
     */
    public void stop() {
        removeCallbacks(play);
    }

    /**
     * 轮播时间间隔
     *
     * @param timeMillis
     */
    public void setTimeMillis(long timeMillis) {
        this.timeMillis=timeMillis;
    }

    /**
     * 轮播方向
     */
    public void setDirection(Direction direction) {
        this.direction=direction;
    }

    public enum Direction {
        LEFT,
        RIGHT
    }

    private long timeMillis = 1000 * 10;
    private Direction direction = Direction.LEFT;

    private Runnable play = new Runnable() {
        @Override
        public void run() {
            play(direction);
        }
    };

    private void play(Direction direction) {
        PagerAdapter adapter = getAdapter();
        if (adapter != null) {
            int count = adapter.getCount();
            int currentItem = getCurrentItem();
            switch (direction) {
                case LEFT:
                    currentItem++;
                    if (currentItem >= count) {
                        currentItem = 0;
                    }
                    break;
                case RIGHT:
                    currentItem--;
                    if (currentItem < 0) {
                        currentItem = count-1;
                    }
                    break;
            }
            setCurrentItem(currentItem);
            start();
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case SCROLL_STATE_IDLE:
                        start();
                        break;
                    case SCROLL_STATE_DRAGGING:
                        stop();
                        break;
                }
            }
        });


    }
}
